var btn = document.getElementById('btn');
var get = document.getElementById('get');
var txt = document.getElementById('txt');

btn.addEventListener('click', function () {
    var xhr = new XMLHttpRequest();
    var url = '/comment?comment=' + txt.value
    xhr.open('GET', url, true)
    xhr.onreadystatechange = function () {
        if (xhr.readyState = 4) {
            if (xhr.status === 200) {
                console.log(xhr)
            }else {
                console.log('error')
            }
        }
    }
    xhr.send()
});

get.addEventListener('click', function () {
    var xhr = new XMLHttpRequest();
    var url = '/getComment'
    xhr.open('GET', url, true)
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                var com = parse(JSON.parse(xhr.response).comment)
                var txt = document.createElement('span');
                txt.innerHTML = com
                document.body.appendChild(txt)
            }else {
                console.log('error')
            }
        }
    }
    xhr.send()
});

var parse = function (str) {
    var results = ""
    try {
        HTMLParser(he.unescape(str, {strict: true}), {
            start: function (tag, attrs, unary) {
                // 标签在此过滤
                if (tag === 'script' || tag === 'style' || tag === 'lilnk' || tag === 'iframe' || tag === 'frame') return
                results += '<' + tag;
                for (let i = 0; i < attrs.length; i++) {
                    // 属性在此过滤
                    if(attrs[i].name === 'onerror' || attrs[i].name === 'onclick') continue
                    results += " " + attrs[i].name + '="' + attrs[i].escaped + '"'
                }
                results += (unary ? "/" : "") + ">"
            },
            end: function (tag) {
                results += "</" + tag + ">"
            },
            chars: function (text) {
                results += text
            },
            comment: function (text) {
                results += "<!--" + text + "-->"
            }
        })
        return results
    } catch (error) {
        console.log('error--->', error)
    } finally {
        console.log('results-->', results)
    }
}